<?php
/**
 * @title 347. 前 K 个高频元素 - 最小堆
 * @author start2004
 */

class iMinHeap extends SplMinHeap{
    public function compare($arr1, $arr2)
    {
        if($arr1[1] == $arr2[1]){
            return 0;
        } elseif($arr1[1] < $arr2[1]) {
            return 1;
        } else {
            return -1;
        }
    }
}

class Solution {

    /**
     * @param Integer[] $nums
     * @param Integer $k
     * @return Integer[]
     */
    function topKFrequent($nums, $k) {
        /**
         * @since 2020-07-30 哈希, 统计数量
         */
        $hashs = [];
        foreach ($nums as $num){
            if(isset($hashs[$num])){
                $hashs[$num] += 1;
            } else {
                $hashs[$num] = 1;
            }
        }

        /**
         * @since 2020-09-07 最小堆
         */
        $heap = new iMinHeap();
        $i = 0;
        $min = null;
        foreach ($hashs as $num=>$count){
            $i++;

            /**
             * @since 2020-09-07 先补充k个元素入堆
             */
            if($i<=$k){
                $heap->insert([$num, $count]);
            } else {
                /**
                 * @since 2020-09-07 获取出现最少次数
                 */
                if($min === null){
                    list($n, $min) = $heap->top();
                } else {}

                /**
                 * @since 2020-09-07 高于最少次数的, 入最小堆
                 */
                if($count > $min){
                    $heap->insert([$num, $count]);

                    /**
                     * @since 2020-09-07 最小值出列
                     */
                    $heap->extract();
                    unset($hashs[$n]);
                    $min = null;
                } else {
                    /**
                     * @since 2020-09-07 非出现频率前k个元素
                     */
                    unset($hashs[$num]);
                }
            }
        }

        /**
         * @return
         */
        return array_keys($hashs);
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.30_10.php
 */
$datas = [
    [[1,1,1,2,2,3], 2],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->topKFrequent($data[0], $data[1]);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
